package domain

import (
	"github.com/lab-online/internal/lab/constant"
	"github.com/lab-online/internal/lab/entity"
)

func (d *Domain) MimoPlot(lab entity.LabEntity) (entity.LabEntity, error) {
	return d.mimo(lab, "plot", constant.StatusMimoPlotting)
}

func (d *Domain) MimoDecode(lab entity.LabEntity) (entity.LabEntity, error) {
	return d.mimo(lab, "decode", constant.StatusMimoDecoding)
}

func (d *Domain) mimo(
	lab entity.LabEntity, path string, execStatusCode uint,
) (entity.LabEntity, error) {
	if lab.GetExperimentID() != 1 {
		return nil, constant.RESTErrCourseLabNotFound
	}

	if err := d.checkEligibility(lab); err != nil {
		return nil, err
	}

	if report, err := d.getExpectedReport(lab, execStatusCode); err != nil {
		return nil, err
	} else {
		lab.MergeReport(report)
	}

	if queue, err := d.getQueue(lab.GetExperimentID(), path); err != nil {
		return nil, err
	} else {
		lab.Update(entity.WithQueue(queue), entity.AddStatusFlag(execStatusCode))
	}

	var err error
	if path == "decode" {
		err = lab.SetupMimoDecodeContent()
	} else {
		err = lab.SetupMimoPlotContent()
	}
	if err != nil {
		return nil, err
	}

	if report, err := d.updateReport(lab); err != nil {
		return nil, err
	} else {
		lab.MergeReport(report)
	}

	return d.mq.ProduceExperiment(lab)
}
